"use client"

import { useState, useEffect, useCallback } from "react"
import {
  connectOKXWallet,
  disconnectWallet,
  isOKXWalletInstalled,
  setupAccountChangeListener,
  type WalletConnectionState,
} from "@/utils/wallet"

export function useWallet() {
  const [walletState, setWalletState] = useState<WalletConnectionState>({
    connected: false,
    account: null,
    error: null,
  })

  const [isConnecting, setIsConnecting] = useState(false)
  const [isWalletInstalled, setIsWalletInstalled] = useState(false)

  // Check if wallet is installed
  useEffect(() => {
    setIsWalletInstalled(isOKXWalletInstalled())
  }, [])

  // Setup listeners for account changes
  useEffect(() => {
    if (isWalletInstalled) {
      setupAccountChangeListener((accounts) => {
        if (accounts.length === 0) {
          // User disconnected their wallet
          setWalletState(disconnectWallet())
        } else {
          // Account changed, update state if we're already connected
          if (walletState.connected && walletState.account) {
            setWalletState((prev) => ({
              ...prev,
              account: prev.account
                ? {
                    ...prev.account,
                    solanaAddress: accounts[0],
                  }
                : null,
            }))
          }
        }
      })
    }
  }, [isWalletInstalled, walletState.connected, walletState.account])

  // Connect wallet function
  const connectWallet = useCallback(async () => {
    setIsConnecting(true)
    setWalletState((prev) => ({ ...prev, error: null }))

    try {
      const result = await connectOKXWallet()
      setWalletState(result)

      // Log the result for debugging
      console.log("Wallet connection result:", result)
    } catch (error: any) {
      console.error("Error in connectWallet:", error)
      setWalletState({
        connected: false,
        account: null,
        error: error.message || "Failed to connect wallet",
      })
    } finally {
      setIsConnecting(false)
    }
  }, [])

  // Disconnect wallet function
  const disconnect = useCallback(() => {
    setWalletState(disconnectWallet())
  }, [])

  return {
    ...walletState,
    isConnecting,
    isWalletInstalled,
    connectWallet,
    disconnect,
  }
}
